package com.jjwxc.jwjskandriod.widget.dialog;

import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.FragmentManager;

import org.jetbrains.annotations.NotNull;

import java.lang.reflect.Field;

/**
 * 判斷狀態可能會出現崩潰的bug
 */
public class BaseDialogFragment extends DialogFragment {

    @Override
    public void show(@NotNull FragmentManager manager, String tag) {
        try {
//			super.show(manager, tag);
            try {
                Field mDismissed = DialogFragment.class.getDeclaredField("mDismissed");
                Field mShownByMe = DialogFragment.class.getDeclaredField("mShownByMe");
                mDismissed.setAccessible(true);
                mShownByMe.setAccessible(true);
                try {
                    mDismissed.set(this,false);
                    mShownByMe.set(this,true);
                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }
            } catch (NoSuchFieldException e) {
                e.printStackTrace();
            }
            manager.beginTransaction()
                    .add(this,tag)
                    .commitAllowingStateLoss();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        }
    }
    /**
     * 注意,不要用super.dismiss(),bug 同上show()
     * super.onDismiss就沒問題
     */
    public void dismissDialog() {
        if ( getActivity() != null && !getActivity().isFinishing() && isAdded()) {
            super.dismissAllowingStateLoss();
        }
    }
}
